<template>
  <view class="page">
    <!-- Tab栏 -->
    <view class="tabs">
      <view 
        class="tab-item" 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="{ active: activeTab === index }"
        @click="switchTab(index)"
      >
        <text class="tab-text">{{ tab }}</text>
        <view class="tab-badge" v-if="getBadgeCount(index) > 0">
          {{ getBadgeCount(index) }}
        </view>
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="search-box">
      <input class="search-input" v-model="keyword" placeholder="搜索订单号/地址/备注" confirm-type="search" @confirm="onSearch" />
      <view class="btn-search" @click="onSearch">搜索</view>
    </view>
    <scroll-view class="order-list" scroll-y lower-threshold="60" @scrolltolower="loadMore">
      <view class="order-item" v-for="order in orderList" :key="order.id" @click="goToDetail(order)">
        <view class="order-header">
          <view class="order-no-wrapper">
            <text class="order-no">订单号：{{ order.orderNo }}</text>
            <text class="order-type-tag" :class="'type-' + (order.orderType || 1)">
              {{ getOrderTypeText(order.orderType) }}
            </text>
          </view>
          <text class="order-status" :style="{ color: getStatusColor(order) }">
            {{ getStatusText(order) }}
          </text>
        </view>

        <view class="order-body">
          <!-- 订单商品 -->
          <view class="order-goods" v-if="order.items && order.items.length > 0">
            <view class="goods-item" v-for="(item, index) in order.items.slice(0, 3)" :key="index">
              <image 
                class="goods-image" 
                :src="item.productImage || '/static/images/product-default.png'"
                mode="aspectFill"
              ></image>
              <view class="goods-info">
                <text class="goods-name">{{ item.productName }}</text>
                <view class="goods-footer">
                  <text class="goods-price">¥{{ item.price }}</text>
                  <text class="goods-quantity">x{{ item.quantity }}</text>
                </view>
              </view>
            </view>
            <view class="goods-more" v-if="order.items.length > 3">
              <text>还有{{ order.items.length - 3 }}件商品...</text>
            </view>
          </view>

          <!-- 配送地址 -->
          <view class="order-address" v-if="order.deliveryAddress">
            <text class="address-icon">📍</text>
            <text class="address-text">{{ order.deliveryAddress }}</text>
          </view>
        </view>

        <view class="order-footer">
          <view class="order-price">
            <text class="price-label">实付</text>
            <text class="price-value">¥{{ order.actualAmount }}</text>
          </view>
          <view class="order-actions">
            <!-- 只有零食订单（orderType=1）才显示操作按钮 -->
            <template v-if="order.orderType === 1">
              <view class="btn btn-default" v-if="order.status === 1" @click.stop="acceptOrder(order)">
                接单
              </view>
              <view class="btn btn-default" v-if="order.status === 1" @click.stop="rejectOrder(order)">
                拒绝
              </view>
              <view class="btn btn-primary" v-if="order.status === 3" @click.stop="finishOrder(order)">
                完成订单
              </view>
            </template>
            <view class="btn btn-danger" v-if="canDelete(order)" @click.stop="deleteOrder(order)">
              删除
            </view>
            <!-- 代取订单（orderType=2,3,4）不显示操作按钮，仅查看 -->
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty" v-if="orderList.length === 0 && !loading">
        <text class="empty-icon">📦</text>
        <text class="empty-text">暂无订单</text>
      </view>

      <!-- 加载更多 -->
      <view class="loadmore" v-if="orderList.length > 0">
        <text class="loadmore-text">{{ loadingText }}</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getOrderStatusDisplay, getStatusColor as getUnifiedStatusColor } from '@/utils/orderStatus'

export default {
  data() {
    return {
      tabs: ['全部', '待接单', '配送中', '已完成'],
      activeTab: 0,
      orderList: [],
      keyword: '',
      badgeCount: {
        waitAccept: 0,
        delivering: 0
      },
      page: 1,
      pageSize: 10,
      loading: false,
      finished: false
    }
  },
  
  // 拦截返回事件
  onBackPress() {
    // 获取页面栈
    const pages = getCurrentPages()
    
    // 如果是从其他页面进来的（页面栈 > 1），使用默认返回
    if (pages.length > 1) {
      return false // 不拦截，使用默认返回行为
    } 
    
    // 如果页面栈只有一层（直接打开），跳转到"我的"Tab
    uni.switchTab({
      url: '/pages/user/index'
    })
    return true // 拦截默认返回行为
  },
  
  computed: {
    loadingText() {
      if (this.loading) return '加载中...'
      if (this.finished) return '没有更多了'
      return '上拉加载更多'
    }
  },
  onLoad() {
    this.loadOrders()
  },
  onShow() {
    // 刷新列表
    this.page = 1
    this.finished = false
    this.loadOrders()
  },
  onPullDownRefresh() {
    this.page = 1
    this.finished = false
    this.loadOrders()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1000)
  },
  methods: {
    getBadgeCount(index) {
      if (index === 1) return this.badgeCount.waitAccept
      if (index === 2) return this.badgeCount.delivering
      return 0
    },
    
    switchTab(index) {
      this.activeTab = index
      this.page = 1
      this.finished = false
      this.orderList = []
      this.loadOrders()
    },
    onSearch() {
      this.page = 1
      this.finished = false
      this.orderList = []
      this.loadOrders()
    },
    
    async loadOrders() {
      if (this.loading || this.finished) return
      
      this.loading = true
      
      try {
        const { getOrderPage } = require('@/api/order')
        
        // 状态映射（统一状态v2.0）
        const statusMap = {
          0: null,  // 全部
          1: 1,     // 待接单
          2: 3,     // 配送中（新状态值为3）
          3: 6      // 已完成（新状态值为6）
        }
        
        const status = statusMap[this.activeTab]
        const params = {
          current: this.page,
          size: this.pageSize
          // 商家作为平台管理者，查看所有订单（零食订单+代取订单）
          // 零食订单可操作，代取订单仅查看
        }
        
        // 只有当status不为null时才添加到参数中
        if (status !== null) {
          params.status = status
        }
        if (this.keyword && this.keyword.trim()) {
          params.keyword = this.keyword.trim()
        }
        
        const pageData = await getOrderPage(params)
        
        //console.log('订单分页数据:', pageData)
        
        const records = pageData.records || []
        
        if (this.page === 1) {
          this.orderList = records
        } else {
          this.orderList.push(...records)
        }
        
        this.loading = false
        
        if (records.length < this.pageSize || this.page >= (pageData.pages || 1)) {
          this.finished = true
        }
        
        // 更新角标
        this.updateBadgeCount()
      } catch (error) {
        console.error('加载订单失败:', error)
        this.loading = false
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    
    async updateBadgeCount() {
      // 统计各状态订单数量（使用新的统一状态码）
      this.badgeCount = {
        waitAccept: this.orderList.filter(o => o.status === 1).length,  // 待接单
        delivering: this.orderList.filter(o => o.status === 3).length   // 配送中
      }
    },
    
    loadMore() {
      if (this.loading || this.finished) return
      this.page++
      this.loadOrders()
    },
    
    goToDetail(order) {
      const orderType = order.orderType || 1
      
      // 零食订单（orderType=1）跳转到零食订单详情页
      if (orderType === 1) {
        uni.navigateTo({
          url: `/pages/order/detail?id=${order.id}`
        })
      } else {
        // 代取订单（orderType=2,3,4）跳转到代取订单详情页
        uni.navigateTo({
          url: `/pages/pickup/detail?orderId=${order.id}`
        })
      }
    },
    
    // 使用统一的状态显示工具（根据订单类型显示状态）
    getStatusText(order) {
      const orderType = order.orderType || 1
      const status = order.status
      const display = getOrderStatusDisplay(orderType, status)
      
      // 调试输出
      if (display.text === '未知') {
        console.warn('商家订单列表-未知状态:', { 
          orderId: order.id, 
          orderNo: order.orderNo,
          orderType, 
          status 
        })
      }
      
      return display.text
    },
    
    getStatusColor(order) {
      const orderType = order.orderType || 1
      const status = order.status
      return getUnifiedStatusColor(orderType, status)
    },
    
    // 获取订单类型文本
    getOrderTypeText(orderType) {
      const types = {
        1: '零食',
        2: '快递',
        3: '外卖',
        4: '奶咖',
        5: '其他服务'
      }
      return types[orderType] || '其他'
    },

    canDelete() {
      return true
    },
    
    acceptOrder(order) {
      uni.showModal({
        title: '接单确认',
        content: '确定接受该订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '处理中...' })
              
              // TODO: 调用接单API
              const { acceptOrder } = require('@/api/order')
              await acceptOrder(order.id)
              
              uni.hideLoading()
              uni.showToast({
                title: '接单成功',
                icon: 'success'
              })
              
              // 刷新列表
              setTimeout(() => {
                this.page = 1
                this.finished = false
                this.orderList = []
                this.loadOrders()
              }, 1500)
            } catch (error) {
              console.error('接单失败:', error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || '接单失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    rejectOrder(order) {
      uni.showModal({
        title: '拒绝订单',
        content: '确定要拒绝该订单吗？',
        editable: true,
        placeholderText: '请输入拒绝原因',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '处理中...' })
              
              const { rejectOrder } = require('@/api/order')
              await rejectOrder(order.id, res.content || '商家拒绝')
              
              uni.hideLoading()
              uni.showToast({
                title: '已拒绝',
                icon: 'success'
              })
              
              // 刷新列表
              setTimeout(() => {
                this.page = 1
                this.finished = false
                this.orderList = []
                this.loadOrders()
              }, 1500)
            } catch (error) {
              console.error('拒绝订单失败:', error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    finishOrder(order) {
      uni.showModal({
        title: '完成订单',
        content: '确认已送达客户吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '处理中...' })
              
              const { finishOrder } = require('@/api/order')
              await finishOrder(order.id)
              
              uni.hideLoading()
              uni.showToast({
                title: '订单已完成',
                icon: 'success'
              })
              
              // 刷新列表
              setTimeout(() => {
                this.page = 1
                this.finished = false
                this.orderList = []
                this.loadOrders()
              }, 1500)
            } catch (error) {
              console.error('完成订单失败:', error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    deleteOrder(order) {
      uni.showModal({
        title: '删除订单',
        content: '确定删除该订单吗？删除后无法恢复。',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '处理中...' })
              const { deleteOrder } = require('@/api/order')
              await deleteOrder(order.id)
              uni.hideLoading()
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })

              setTimeout(() => {
                this.page = 1
                this.finished = false
                this.orderList = []
                this.loadOrders()
              }, 1200)
            } catch (error) {
              console.error('删除订单失败:', error)
              uni.hideLoading()
              uni.showToast({
                title: error.message || '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    markDelivering(order) {
      uni.navigateTo({
        url: `/pages/merchant/delivery?orderId=${order.id}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* Tab栏 */
.tabs {
  background: #fff;
  display: flex;
  padding: 0 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;
}

.search-box {
  display: flex;
  gap: 16rpx;
  padding: 20rpx;
  background: #fff;
}

.search-input {
  flex: 1;
  height: 72rpx;
  padding: 0 24rpx;
  border-radius: 36rpx;
  background: #f5f7fa;
  font-size: 26rpx;
}

.btn-search {
  width: 140rpx;
  height: 72rpx;
  border-radius: 36rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
}

.tab-item {
  flex: 1;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  .tab-text {
    font-size: 28rpx;
    color: #666;
    transition: all 0.3s;
  }
  
  .tab-badge {
    position: absolute;
    top: 12rpx;
    right: 20rpx;
    background: #ff4d4f;
    color: #fff;
    font-size: 20rpx;
    padding: 4rpx 8rpx;
    border-radius: 20rpx;
    min-width: 32rpx;
    text-align: center;
  }
  
  &.active {
    .tab-text {
      color: #667eea;
      font-weight: bold;
    }
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 6rpx;
      background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
      border-radius: 3rpx;
    }
  }
}

/* 订单列表 */
.order-list {
  flex: 1;
  height: 0;
  padding: 20rpx;
}

.order-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .order-no-wrapper {
    display: flex;
    align-items: center;
    gap: 12rpx;
  }
  
  .order-no {
    font-size: 24rpx;
    color: #999;
  }
  
  .order-type-tag {
    font-size: 20rpx;
    padding: 4rpx 12rpx;
    border-radius: 8rpx;
    font-weight: bold;
    
    &.type-1 {
      background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
      color: #fff;
    }
    
    &.type-2 {
      background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
      color: #fff;
    }
    
    &.type-3 {
      background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
      color: #fff;
    }
    
    &.type-4 {
      background: linear-gradient(135deg, #d299c2 0%, #fef9d7 100%);
      color: #fff;
    }
    
    &.type-5 {
      background: linear-gradient(135deg, #a8e6cf 0%, #dcedc1 100%);
      color: #fff;
    }
  }
  
  .order-status {
    font-size: 26rpx;
    font-weight: bold;
  }
}

.order-body {
  padding: 24rpx 0;
}

.order-goods {
  margin-bottom: 20rpx;
}

.goods-item {
  display: flex;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.goods-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 8rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 26rpx;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.goods-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-price {
  font-size: 26rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.goods-quantity {
  font-size: 24rpx;
  color: #999;
}

.goods-more {
  font-size: 24rpx;
  color: #999;
  text-align: center;
  padding: 8rpx 0;
}

.order-address {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 16rpx;
  background: #f5f7fa;
  border-radius: 8rpx;
  
  .address-icon {
    font-size: 28rpx;
  }
  
  .address-text {
    flex: 1;
    font-size: 24rpx;
    color: #666;
    line-height: 1.6;
  }
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.order-price {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
  
  .price-label {
    font-size: 24rpx;
    color: #999;
  }
  
  .price-value {
    font-size: 32rpx;
    font-weight: bold;
    color: #ff6b6b;
  }
}

.order-actions {
  display: flex;
  gap: 16rpx;
}

.btn {
  padding: 12rpx 28rpx;
  border-radius: 40rpx;
  font-size: 24rpx;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
  }

  &.btn-danger {
    background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
    color: #fff;
  }
}

/* 空状态 */
.empty {
  padding: 120rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 32rpx;
  
  .empty-icon {
    font-size: 160rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 加载更多 */
.loadmore {
  padding: 40rpx 20rpx;
  text-align: center;
  
  .loadmore-text {
    font-size: 24rpx;
    color: #999;
  }
}
</style>

